package vn.com.unit.springmvc.mvc;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import vn.com.unit.springmvc.domain.Vendor;
import vn.com.unit.springmvc.repo.VendorDao;

@Controller
@RequestMapping(value = "/vendor")
public class VendorController {
	@Autowired
	private VendorDao vendorDao;

	@RequestMapping(method = RequestMethod.GET)
	public String displaySortedVendor(Model model) {
		model.addAttribute("newVendor", new Vendor());
		model.addAttribute("vendors", vendorDao.findAllOrderedByName());
		return "vendor/index";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String registerNewVendor(
			@Valid @ModelAttribute("newVendor") Vendor newVendor,
			BindingResult result, Model model) {
		if (!result.hasErrors()) {
			vendorDao.register(newVendor);
			return "redirect:/vendor";
		} else {
			model.addAttribute("vendors", vendorDao.findAllOrderedByName());
			return "vendor/index";
		}

	}

	@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
	public String viewVendorById(@PathVariable("id") Long id, Model model) {
		Vendor obj = vendorDao.findById(id);
		model.addAttribute("vendor", obj);
		return "vendor/view";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String editVendoById(@PathVariable("id") Long id, Model model) {
		Vendor obj = vendorDao.findById(id);
		model.addAttribute("editVendor", obj);
		model.addAttribute("isEdit", true);
		return "vendor/view";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	public String deleteVendorById(@PathVariable("id") Long id, Model model) {
		vendorDao.delete(id);
		return "redirect:/vendor";
	}
}
